﻿//单独播放器页面
$(function(){
	$(".openList").click(function(){
		$("#playerLrc").attr("scorllVal",$(document).scrollTop())//记录之前的滚动条位置
		$("#playerLrc").hide();
		$("#playerList").show();
        $("html,body").animate({scrollTop:$("#playerList .current").offset().top-90},600); 
		$(".topBack").addClass("topBackNew");
        })
	$("#closePlayerList").click(function(){
		$(".topBack").removeClass("topBackNew");
		$("#playerList").hide();
		$("#playerLrc").show();
		$("html,body").animate({scrollTop:$("#playerLrc").attr("scorllVal")},600); 
        })
	$(".topBackNew").live("click",function(){
		$(".topBack").removeClass("topBackNew");
		$("#playerList").hide();
		$("#playerLrc").show();
		$("html,body").animate({scrollTop:$("#playerLrc").attr("scorllVal")},600);
		return false;
        })	
	
});

//集成到页面的播放器
$(function(){
	//playerAlert("请选择歌曲或点击播放按钮");
	$(".openLrc").click(function(){
		if($("#musicList").find(".current").length>0){
		$(".openLrc").attr("scorllVal",$(document).scrollTop());//记录之前的滚动条位置
		$("#songBox").hide();
		$("#viewLrc").show();
		$(".topTit").html($("#musicList li.current strong a").text());
		$(".topBack").addClass("topBackNew");
		}
		else{
		alertText("当前没有歌曲正在播放!")
		}	
      })
	  
	  $(".jp-play").click(function(){
		if($("#musicList").find(".current").length>0){
		}
		else{
		alertText("当前没有歌曲正在播放!")
		}	
      })
	
	$(".topBackNew").live("click",function(){
		$(".topBack").removeClass("topBackNew");
		$("#viewLrc").hide();
		$("#songBox").show();
		$("html,body").animate({scrollTop:$(".openLrc").attr("scorllVal")},600); 
		$(".topTit").html($(".topTit").attr("defaulttit"));
		return false;
        })
	$("#closeLrc").click(function(){
		$(".topBack").removeClass("topBackNew");
		$("#viewLrc").hide();
		$("#songBox").show();
		$("html,body").animate({scrollTop:$(".openLrc").attr("scorllVal")},600); 
		$(".topTit").html($(".topTit").attr("defaulttit"));
		return false;
        })	
		
	$("#musicList li").click(function(){
		$(this).addClass("current").siblings().removeClass("current");
		$("html,body").animate({scrollTop:$("#musicList .current").offset().top-150},400);
		clearTimeout(cl);
		clearTimeout(cl2);
		canplay=1;pu.utils(0,$(this).index(),1);
	})	
	//循环模式切换	
	$("#xunShunxu").click(function(){
		$(this).hide();
		$("#xunDanqu").show();
		alertText("已切换到单曲播放")
		PlayMethod(1);
	});	
	$("#xunDanqu").click(function(){
		$(this).hide();
		$("#xunSuiji").show();
		alertText("已切换到随机播放")
		PlayMethod(2);
	});
	$("#xunSuiji").click(function(){
		$(this).hide();
		$("#xunShunxu").show();
		alertText("已切换到顺序播放")
		PlayMethod(0);
	});
	
});
/*播放器相关*/
var addrlocation=document.URL.toLowerCase();
if(addrlocation.indexOf(".9ku.com")!=-1)document.domain="9ku.com";
if(addrlocation.indexOf("?qq-pf-to")!=-1)addrlocation=addrlocation.split("?qq-pf-to")[0];
var meida={mp3:""};
var $referrer=document.referrer.toLowerCase();//来源网址
var isIE=false;//document.all? true:false;
var $song_Lrc = new Array();//Lrc歌词
var $song_Lrci = new Array();//排序后的lrc时间
var $data_Url = new Array();//存放文件路径
var id_list=0;//列表文件编号
var id_list_play=0;//当前播放列表编号
var id_list_fy=1;//列表分页，默认第一页
var song_play_id=0;//当前播放的歌曲id
var song_gs_id=0;//当前播放的歌手id
var song_qumu_id=0;//当前播放第几首
var fast=false;//禁止鼠标快速切换
var maxperpage=12;//每页记录数
var totalpage=1,currentPage=1;//初始化默认总页数和当前页
var _url = "http://www.9ku.com";//当前域
var playlrcid;//lrc歌词定时器
var playbfqid;//播放器定时器
var isloadlrc,loadlrcnum=0;//初始化lrc歌词是否加载成功
var oldsokey="";//搜索关键词
var isTmpList=0;//0临时列表,1播放历史
var timeupd1=0,timeupd2=0;//时间进度
/*初始化变量结束*/

//数字判断函数
function IsNum(s){return(new RegExp(/^(\+|-)?(0|[1-9]\d*)(\.\d*[1-9])?$/).test(s));}
function formatFloat(src, pos){ var gyc= Math.round(src*Math.pow(10, pos))/Math.pow(10, pos);if(src>gyc){return gyc+1;}else{return gyc;}}
function $waitbehind(b){if(document.getElementById("musicList"))document.getElementById('musicList').innerHTML= '<div id="landing"><div id="lan"><div class="h3"><p>'+b+'</p></div></div></div>';}
function slTop(b){if(document.getElementById("musicList"))document.getElementById("musicList").scrollTop=b;}
function $download(URL){if(URL==undefined)return;Tag = document.createElement("script");Tag.type="text/javascript";Tag.src=URL;document.getElementsByTagName("head")[0].appendChild(Tag);}
function $downloadgbk(URL){if(URL==undefined)return;Tag = document.createElement("script");Tag.type="text/javascript";Tag.charset="gb2312";Tag.src=URL;document.getElementsByTagName("head")[0].appendChild(Tag);}
function PlayMethod(v) {if(document.getElementById("Playleixin"))document.getElementById("Playleixin").value = v;return;}

//播放器
function PlayerUtils() {
	var p = 0;//播放序号
	var song_id;//上一首歌曲id
	var song_u = new Array();
	var rnd_id = 0;//随机播放序号
	var total = 0;//总歌曲数
	var lrctimea = 8888888;

	//播放完下一首
	this.playnextsong = function() {
		timeupd2 = 0;
		var leixin = document.getElementById('Playleixin').value;
		if (leixin == 0) {
			this.PlayNext(1);
		} else if (leixin == 1) {
			this.PlayNext(0);
		} else if (leixin == 2) {
			this.utils(id_list_play, rnd_id, 0);
		}
	};
	this.ssPlay = function() {
		fast = false;
		try {
			var leixin = document.getElementById('Playleixin').value;
		} catch(e) {
			return (false);
		}
		if (leixin == 2) {
			if (rnd_id >= total - 1) {
				rnd_id = 0;
			} else {
				rnd_id++;
			}
		}
		playbfqid = setTimeout("pu.ssPlay()", 200);
	};
	this.PlayNext = function(t) {
		timeupd2=0;
		this._Next(t);
	};
	this._Next = function(t) {
		p += t;
		if (p > (total - 1)) {
			p = 0;
		} else if (p < 0) {
			p = (total - 1);
		}
		this.utils(id_list_play, p, 0);
	};
	//t列表编号,r第几首,s备用
	this.utils = function(t, r, s) {
		timeupd2=0;
		clearTimeout(playlrcid);
		playlrcid = setTimeout("pu.PlayLrc()", 200);
		if (fast) {
			return (false);
		}
		fast = true;
		if ($song_data[t]) {
			var song_data = $song_data[t].split('||');
			total = song_data.length - 1;
			song_u = song_data[r].split('|');	
			p = r;
			if(document.getElementById("#songBox")){
				if($("#songBox").is(":hidden")){
					$(".topTit").html(song_u[1]);
				} 
			}else{
				$(".topTit").html(song_u[1]);
			}
			if(document.getElementById("singer_name"))$("#singer_name").html("<a href=\"/geshou/"+song_u[2]+".htm\">"+song_u[3]+"</a>");
			var album_link="";
			if(song_u[5]!=0)album_link="<a href=\"/zjmusic/"+song_u[5]+".htm\">《"+song_u[6]+"》</a>"
			if(document.getElementById("music_name"))$("#music_name").html(album_link);
			this.downloadlrc(song_u[0]);//下载歌词
			//定位到第几页并改变背景色
			this.changeBg(r,t,song_id,song_u[0]);
			song_id=song_u[0];
			eval("song_qumu_id=r");
			eval("song_play_id=song_id");
			eval("id_list_play=t");
			eval("song_gs_id=" + song_u[2]);
			//加载播放器开始播放
			var wmaurl=song_u[4];
			if(wmaurl.indexOf("http://")==-1){
				wmaurl=DzUrl+wmaurl;
			}
			Media_wma(wmaurl);
			var tpath=Math.ceil(song_u[2]/10000);
			if(document.getElementById("pic"))$("#pic").attr("src",img9ku+"/pic/gstx/"+tpath+"/"+song_u[2]+".jpg");
		}
	};
	// r第几首歌曲，t列表编号,song_id上一首歌曲id,song_u当前歌曲id
	this.changeBg = function(r, t, song_id, song_u) {
		if (t == id_list) {
			var gy = formatFloat((r + 1) / maxperpage, 0);
			if (gy == 1) {
				xx = (r - 0);
			} else {
				xx = r - (maxperpage * (gy - 1));
			}
			if (gy == id_list_fy) {
				slTop((xx - 5) * 22);
			}
			if (document.getElementById('song_' + song_id + '_p')) {
				document.getElementById('song_' + song_id + '_p').className = "";
			}
			if (document.getElementById('song_' + song_u + '_p')) {
				document.getElementById('song_' + song_u + '_p').className = "current";
				var scrollValNext=$('#song_' + song_u + '_p').offset().top
				$("html,body").stop().animate({scrollTop:scrollValNext-150},600); 
			}
		}
	};
	this.led = function(s1, s2, s3, s4, s5, s6, s7) {
		document.getElementById("LR1").innerHTML = s1;
		document.getElementById("LR2").innerHTML = s2;
		document.getElementById("LR3").innerHTML = s3;
		document.getElementById("LR4").innerHTML = s4;
		document.getElementById("LR5").innerHTML = s5;
		document.getElementById("LR6").innerHTML = s6;
		document.getElementById("LR7").innerHTML = s7;
	};
	this.downloadlrc = function(t) {
		if (!IsNum(t)) return;
		var tfolder = Math.ceil(t / 10000).toString();
		if (!$song_Lrc[t]) {
			this.led('', '', '', '正在载入歌词...', '', '', '');
			var tpath=Math.ceil(t/10000);
			$downloadgbk('http://www.9ku.com/html/lrc/' + tpath + '/' + t + '.js');
			isloadlrc = setTimeout("pu.checklrcisload(" + t + ")", 3000);
		}
		lrctimea = 8888888;
	};
	this.doSp = function(oT) {
		if (parseInt(oT) > 1) {
			var zongsj = $(".jp-duration").html();
			var b1 = zongsj.split(":");
			var b2 = b1[0];
			var b3 = b1[1];
			b2 = parseFloat(b2);
			b3 = parseFloat(b3);
			var b4 = b2 * 60 + b3;
			b4 = parseFloat(b4);
			var rat = 460 / b4;
			rat = parseFloat(rat);
			$("#kuPlayer").jPlayer("playHead", 100 * (oT / 460 * rat));
		}
	};
	this.lrci = function(xi, i) {
		if (_l[i]) {
			var l_path = _t[i] / 1000;
			document.getElementById(xi).innerHTML = '<a style="CURSOR: pointer" onclick="pu.doSp(\'' + l_path + '\')" >' + _l[i] + '</a>';
		} else {
			document.getElementById(xi).innerHTML = '';
		}
	};
	this.PlayLrc = function() {
		var nolrc = false;
		if ($song_Lrc[song_id]) {
			try {
				var bfqtime = $(".jp-current-time").html();
				var b1 = bfqtime.split(":");
				var b2 = b1[0];
				var b3 = b1[1];
				b2 = parseFloat(b2);
				b3 = parseFloat(b3);
				var b4 = b2 * 60 + b3;
				b4 = parseFloat(b4);
				var curTime = b4 * 1000 + 500;
			} catch(e) {
				var curTime = 0;
			}
			if ($song_Lrc[song_id] == 0) {
				if (8888888 == lrctimea) {
					this.led('', '<span style="color: #FF9900">歌手：' + song_u[3] + '</span>', '<span style="color: #FF9900">歌曲：' + song_u[1] + '</span>', '没找到相关歌词', '');
				}
				lrctimea = 0;
				nolrc = false;
			} else if ($song_Lrc[song_id].indexOf("文本歌词[/]") != -1) {
				lrctimea = 0;
				nolrc = true;
				try {
					document.getElementById("lyric").style.display = "none";
					document.getElementById("txtword").style.display = "block";
					var textword = $song_Lrc[song_id].split("[/]")[1].replace('　', '');
					textword = textword.replace(/\&lt;/g, "<");
					textword = textword.replace(/\&gt;/g, ">");
					textword = textword.replace(/\&nbsp;/g, " ");
					document.getElementById("txtword").innerHTML = textword;
				} catch(e) {
					return (false);
				}
				if ($song_Lrc[song_id].indexOf("暂时找不到这首歌曲的歌词") != -1) {
					document.getElementById("txtword").style.overflowY = "hidden";
				} else {
					document.getElementById("txtword").style.overflowY = "";
				}
			} else if ($song_Lrc[song_id].length > 0) {
				nolrc = false;
				try {
					document.getElementById("lyric").style.display = "block";
					document.getElementById("txtword").style.display = "none";
				} catch(e) {
					return (false);
				}
				if (8888888 == lrctimea) {
					if ($song_Lrci[song_id]) {} else {
						var lrc1 = $song_Lrc[song_id].split("[");
						var array = [];
						for (var i = 0; i < lrc1.length; i++) {
							var g = {};
							var t = lrc1[i].split("]");
							g.time = jtime(t[0]);
							if (isNaN(g.time)) continue;
							g.c = t[1];
							if (g.c == "") g.c = getnext(i, lrc1);
							array.push(g);
						}
						array.sort(function(x, y) {
							if (x.time > y.time) return 1;
							else if (x.time < y.time) return - 1;
							else return 0;
						});
						$song_Lrci[song_id] = array;
					}
					var tin = "";
					var tim = "";
					if ($song_Lrci[song_id]) {
						var array1 = $song_Lrci[song_id];
						for (var i = 0; i < array1.length; i++) {
							var g = array1[i];
							if (!g.c) {
								g.c = "";
							}
							tin += g.time;
							tim += g.c;
							if (i < array1.length - 1) {
								tin += ",";
								tim += "[n]";
							}
						}
					}
					var timeH = '0,0,0,0,' + tin + ',8888888';
					tim = tim.replace("&amp;", "&");
					var TxtH = '歌手：' + song_u[3] + '[n]歌曲：' + song_u[1] + '[n][n]支持九酷音乐，就把9ku.com推荐给三个QQ好友[n]' + tim + '[n]九酷音乐网';
					_t = timeH.split(",");
					_l = TxtH.split('[n]');
				}
				for (var i = 0; i < _t.length; i++) {
					if (_t[i] < curTime && curTime < _t[i + 1] || 8888888 == lrctimea) {
						if (lrctimea != i) {
							this.lrci("LR1", i - 3);
							this.lrci("LR2", i - 2);
							this.lrci("LR3", i - 1);
							this.lrci("LR4", i);
							this.lrci("LR5", i + 1);
							this.lrci("LR6", i + 2);
							this.lrci("LR7", i + 3);
						}
						lrctimea = i;
					}
				}
			} else {
				if (8888888 == lrctimea) {
					this.led('','', '', '载入歌词失败！', '','', '');
					lrctimea = 0;
					nolrc = false;
				}
			}
		}
		if (nolrc) {
			clearTimeout(playlrcid);
		} else {
			playlrcid = setTimeout("pu.PlayLrc()", 100);
		}
	};
	this.checklrcisload = function(t) {
		if (!$song_Lrc[t]) {
			loadlrcnum += 1;
			if (loadlrcnum > 3) {
				loadlrcnum = 0;
				clearTimeout(isloadlrc);
			} else {
				isloadlrc = setTimeout("pu.downloadlrc(" + t + ")", 3000);
			}
		} else {
			loadlrcnum = 0;
			clearTimeout(isloadlrc);
		}
	};	
}
function Media_wma(src) {
	meida.mp3=src;
	if(canplay==1){
		$("#kuPlayer").jPlayer("setMedia", meida).jPlayer("play");
	}else{
		$("#kuPlayer").jPlayer("setMedia", meida);	
	}
}
function getnext(y, lrc) {
	var result = "";
	var i = y + 1;
	if (lrc[i]) {
		t = lrc[i].split("]");
		if (t[1] == "") result = getnext(i, lrc);
		else result = t[1]
	}
	return result;
};

function jtime(tn) {
	var time = 0;
	var ta = tn.split(":");
	if (ta.length < 2) return time;

	if (ta[1].indexOf(".") > 0) {
		var tb = ta[1].split(".");
		time = ta[0] * 60 * 1000 + tb[0] * 1000 + tb[1] * 10;
	} else time = ta[0] * 60 * 1000 + ta[1] * 1000;
	return time;
}

$(function() {
	$("#kuPlayer").jPlayer({
		ready: function(event) {
			$("#kuPlayer").jPlayer("setMedia", meida).jPlayer("play");
		},
		timeupdate: function(obj) {
			timeupd1 = Math.floor(obj.jPlayer.status.currentTime);
			if (timeupd1 <= 10) {
				timeupd2 += 1;
			} else {
				timeupd2 = 0;
			}
		//	if (timeupd2 >= 10 && timeupd1 == 0) {
		//		$("#play_musicname").html("不能播放");
		//		pu.playnextsong();
		//	}
		},
		supplied: "mp3",
		swfPath: "/script",
		solution: "html,flash",
		wmode: "window",
		volume: 1,
		ended: function() {
			downlog(song_play_id,3,timeupd1);
			pu.playnextsong();
		}/*,
		error: function(event) {
			if (event.jPlayer.error.type == "e_url") {
				playerAlert("播放错误，5秒后自动跳到下一首");
				setTimeout('pu.playnextsong()',5000);
				
			}
		}*/,
		playing:function(){canplay=1;}
	});
	
	$("#kuPlayer").bind($.jPlayer.event.loadstart,function(event) {
		playerAlert("请点击播放按钮！"); //单播出现
	});
	
	$("#kuPlayer").bind($.jPlayer.event.loadedmetadata, function(event) {
		playerAlert("载入歌曲");
		$("#playerNotice").fadeOut(10000,function(){$(this).remove();}); 
	});
	
	$("#kuPlayer").bind($.jPlayer.event.pause, function(event) { 
		playerAlert("播放暂停");
	});
	
	//$("#kuPlayer").bind($.jPlayer.event.play, function(event) {
		//playerAlert("开始播放1111");
		//$("#playerNotice").fadeOut(3000,function(){$(this).remove();}); 
	//});
	$("#kuPlayer").bind($.jPlayer.event.playing, function(event) {
		playerAlert("开始播放");
		$("#playerNotice").fadeOut(10000,function(){$(this).remove();}); 
	});

});

/*需要在页面底部调用部分*/
var bang=0,dwid=0,checknums=0,checknogq=0,issuiji=0;
id_list=bang;
id_list_play=bang;
var cl=setTimeout("checkloaded();",200);
var cl2=0;
var cled=false;
var pu = new PlayerUtils();pu.ssPlay();

function checkloaded() {
	if ($song_data[bang]) {
		var c = $song_data[bang];
		var x = c.split("||");
		if (issuiji == 1) {
			dwid = x[Math.round(Math.random() * x.length - 1)].split("|")[0];
			if (IsNum(dwid)) {
				song_play_id = dwid;
			}
		} else {
			dwid = x[0].split("|")[0];
		}
		for (var i = 0; i < x.length - 1; i++) {
			if (dwid > 0 && dwid == x[i].split("|")[0]) {
				if(canplay==1)pu.utils(bang, i, 1);
				cled = true;
				song_qumu_id = i;
				//alert('开始播放，定位');
				break;
			}
		}
		if (cled == false) {
			checknums += 1;
			//alert("加载失败，继续加载");
			if(canplay==1)pu.utils(bang, 0, 1);
			cl = setTimeout("checkloaded();", 200);
		} else {
			clearTimeout(cl);
		}
	} else {
		cl = setTimeout("checkloaded();", 200);
	}
}
cl2=setTimeout(function(){
	var jp_current_time=$(".jp-current-time").html();
	if(jp_current_time=="00:00"){
		clearTimeout(cl2);
		//alert("播放时间为0，继续加载")
		cl=setTimeout("checkloaded();",200);
	}
},500);   //这个秒是做什么的？ 10000